Icaro - Compressor

  • Created by Andrés Segura Tinoco
  • Created on June 17, 2019
In [1]:
# Load Python libraries
import io
import numpy as np
import pandas as pd
from collections import Counter
from PIL import Image
In [2]:
# Load Plot libraries
import seaborn as sns
import matplotlib.pyplot as plt
In [3]:
# Loading an example image
file_path = "../data/img/example-1.png"
img = Image.open(file_path)
In [4]:
# Show image dimension (resolution)
img.size
Out[4]:
(1920, 1080)
In [5]:
# Show image extension
img.format
Out[5]:
'PNG'
In [6]:
# Show image
img
Out[6]:
In [7]:
# Read file in low level (bit list)
with open(file_path, 'rb') as f:
    low_byte_list = bytearray(f.read())
In [8]:
# Show size (KB)
round(len(low_byte_list) / 1024, 2)
Out[8]:
2728.96
In [9]:
# Show size (MB)
round(len(low_byte_list) / 1024 / 1020, 2)
Out[9]:
2.68
In [10]:
# Create a matrix
row_len = 2232
col_len = 1252
matrix = np.zeros((row_len, col_len))
matrix.shape
Out[10]:
(2232, 1252)
In [11]:
# Calculate additional bits
gap = np.prod(matrix.shape) - len(low_byte_list)
gap
Out[11]:
6
In [12]:
# Save bytes into matrix
data = np.array(low_byte_list)
for i in range(0, len(data)):
    ix_row = int(i / col_len)
    ix_col = i % col_len
    matrix[ix_row][ix_col] = data[i]
In [13]:
# Plot image in binary
fig, ax = plt.subplots(figsize = (14, 14))
sns.heatmap(matrix, ax = ax)
ax.set_title("Bytes of the Image", fontsize = 16)
ax.set_xlabel('columns', fontsize = 12)
ax.set_ylabel('rows', fontsize = 12)
plt.show()

Bytes Distribution

In [14]:
# Calculate code frequency
term_freq = Counter(low_byte_list)
n = len(term_freq)
n
Out[14]:
256
In [15]:
# Normalize term frequency
N = sum(term_freq.values())
for term in term_freq:
    term_freq[term] = term_freq[term] / N
In [16]:
# Create a temp dataframe
df = pd.DataFrame.from_records(term_freq.most_common(n), columns = ['Byte', 'Frequency'])
df.head(10)
Out[16]:
Byte Frequency
0 68 0.005283
1 34 0.005271
2 221 0.005159
3 102 0.005149
4 17 0.005098
5 238 0.005066
6 0 0.005039
7 204 0.005013
8 136 0.004966
9 247 0.004949
In [17]:
# Create pretty x axis labels
x_labels = []
for ix in range(256):
    if ix % 5 == 0:
        x_labels.append(str(ix))
    else:
        x_labels.append('')
In [18]:
# Plot the frequency of the bytes in the file
fig = plt.figure(figsize = (18, 6))
ax = sns.barplot(x = 'Byte', y = 'Frequency', data = df.sort_values(by=['Byte']), palette=("Blues_d"))
ax.set_xticklabels(labels = x_labels, fontsize = 10, rotation = 50)
plt.title('Bytes Frequency of the Image')
plt.show()

Huffman Code

In [ ]:
 

Metrics

  • Time
  • Size
  • Distribution type: normal, uniform
  • Entropy
  • Parallelism
In [19]:
# Create a new image
# file_path = "../data/img/example-2.png"
# new_img = Image.open(io.BytesIO(low_byte_list))
# new_img.save(file_path)